package com.rex.saas.utils;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import java.util.Base64;
public class Sm2CryptoUtil {

    public static final String publicKeyBase64 =
            "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEf9yV8O3yzfU3D4uhxd1UU24cUT1nmxJzOtPxvKdn3uMNYpVvyFrbPtyVnlFS4CbiAM54xecIy3jKLlLTzB3fLA==";
    public static final String privateKeyBase64 =
            "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgc8Emp7Cq+VxGtJQ1pU9S6QoOGHdbntkTQmCU6/x1/" +
                    " 5GgCgYIKoEcz1UBgi2hRANCAAR/3JXw7fLN9TcPi6HF3VRTbhxRPWebEnM60/G8p2fe4w1ilW/IWts+3JWeUVLgJu" +
                    " IAznjF5wjLeMouUtPMHd8s";

    /**
     * 使⽤公钥加密
     */
    public static String encrypt(String data, String publicKeyBase64) {
        try {
            SM2 encryptSm2 = new SM2(null, publicKeyBase64);
            byte[] encryptData = encryptSm2.encrypt(data.getBytes(), KeyType.PublicKey);
            return Base64.getEncoder().encodeToString(encryptData);
        } catch (Exception e) {
            throw new RuntimeException("SM2加密失败", e);
        }
    }

    /**
     * 使⽤指定私钥解密
     */
    public static String decrypt(String encryptedDataBase64, String privateKeyBase64) {
        try {
            SM2 decryptSm2 = new SM2(privateKeyBase64, null);
            byte[] encryptData = Base64.getDecoder().decode(encryptedDataBase64);
            byte[] decryptData = decryptSm2.decrypt(encryptData, KeyType.PrivateKey);
            return new String(decryptData);
        } catch (Exception e) {
            throw new RuntimeException("SM2解密失败", e);
        }
    }

    public static void main(String[] args) {
        System.out.println("公钥Base64: " + publicKeyBase64);
        System.out.println("私钥Base64: " + privateKeyBase64);
        Sm2CryptoUtil sm2CryptoUtil = new Sm2CryptoUtil();
        // 测试加密解密
        String testData = "{\\\"VendorCode\\\":\\\"Rexense\\\",\\\"Timestamp\\\":\\\"1763456510\\\",\\\"Seq\\\":\\\"1\\\",\\\"GatewayServer\\\":\\\"00E269A1F048\\\",\\\"GateWayId\\\":\\\"C49894C293FA\\\",\\\"DeviceName\\\":\\\"2c16bdd1a4b6_1_1\\\",\\\"FunctionCode\\\":\\\"WriteDevPropertyList\\\",\\\"Payload\\\":{\\\"PowerSwitch_1\\\":\\\"1\\\",\\\"PowerSwitch_2\\\":\\\"1\\\",\\\"PowerSwitch_3\\\":\\\"1\\\",\\\"PowerSwitch_4\\\":\\\"1\\\"}}";
        String encryptedData = sm2CryptoUtil.encrypt(testData, publicKeyBase64);
        System.out.println("加密后: " + encryptedData);
        String decryptedData = sm2CryptoUtil.decrypt(encryptedData,
                privateKeyBase64);
        System.out.println("解密后: " + decryptedData);
    }
}